import { FormattedMessage, formatMessage } from 'umi';
import React, { Component } from 'react';
import {Input, List, Button, message, Modal, Form, Divider, Badge} from 'antd';
import axios from "@/components/Axios/axios";

const passwordStrength = {
  strong: (
    <span className="strong">
      <FormattedMessage id="userset.security.strong" defaultMessage="Strong" />
    </span>
  ),
  medium: (
    <span className="medium">
      <FormattedMessage id="userset.security.medium" defaultMessage="Medium" />
    </span>
  ),
  weak: (
    <span className="weak">
      <FormattedMessage id="userset.security.weak" defaultMessage="Weak" />
      Weak
    </span>
  ),
};

class SecurityView extends Component {
  state = {
   pwdInputVisible: false,
   phoneInputVisible: false,
   questionVisible: false,
   emailVisible: false,
   user: null,
   backupQuestion: {
     question: '',
     answer: ''
   }
  }
  componentDidMount(){
    let user = JSON.parse(sessionStorage.getItem('user'));
    let backupQuestion;
    if (typeof user.backupQuestion == 'string'){
      backupQuestion = {
        question: user.backupQuestion != '' ? user.backupQuestion.split(':')[0] : '',
        answer: user.backupQuestion != '' ? user.backupQuestion.split(':')[1] : ''
      }
    }else {
      backupQuestion = user.backupQuestion;
    }
    this.setState({
      user: JSON.parse(sessionStorage.getItem('user')),
      backupQuestion: backupQuestion
    })
  }
  refreshUser = () => {
    axios.get('/joker/users/getCurrentUser').then(e => {
      let userInfo = e;
      let backupQuestion = {
        question: userInfo.backupQuestion && userInfo.backupQuestion.split(':')[0],
        answer: userInfo.backupQuestion && userInfo.backupQuestion.split(':')[1]
      }
      sessionStorage.setItem('user', JSON.stringify(userInfo));
      this.setState({
        user: userInfo,
        backupQuestion: backupQuestion
      });
    })
  }
  chgVis = () => {
    this.setState({pwdInputVisible: true});
  }
  chgVis2 = () => {
    this.setState({phoneInputVisible: true});
  }
  chgVis3 = () => {
    this.setState({questionVisible: true});
  }
  chgVis4 = () => {
    this.setState({emailVisible: true});
  }
  cancleVis = () => {
    this.setState({questionVisible: false});
  }
  chgPwd = () => {
    const { user } = this.state;
    let pwd = document.getElementById('pwd').value;
    let values = {
      id: user.id,
      password: pwd
    }
    if (pwd.trim() == '' || pwd.trim() == null) {
      message.warn('未输入密码！');
      this.setState({pwdInputVisible: false});
    }else {
      axios.post('joker/users/update',{...values}).then(res => {
        let resposone = JSON.parse(res.request.response);
        if (resposone.Message){
          message.warning(resposone.Message);
        }else if (resposone.status == 1){
          this.refreshUser();
          this.setState({pwdInputVisible: false});
          message.success('修改成功！');
        }else {
          message.error('修改失败！');
        }
      })
    }
  }
  chgPhone = () => {
    const { user } = this.state;
    let phone = document.getElementById('phone').value;
    let values = {
      id: user.id,
      backupPhone: phone
    }
    if (phone.trim() == '' || phone.trim() == null) {
      message.warn('未输入手机号！');
      this.setState({phoneInputVisible: false});
    }else if(!(/^1[3456789]\d{9}$/.test(phone))){
      message.error('手机号有误！请重新输入');
      this.setState({phoneInputVisible: false});
    }else {
      axios.post('joker/users/update',{...values}).then(res => {
        let resposone = JSON.parse(res.request.response);
        if (resposone.Message){
          message.warning(resposone.Message);
        }else if (resposone.status == 1){
          this.refreshUser();
          this.setState({phoneInputVisible: false});
          message.success('修改成功！');
        }else {
          message.error('修改失败！');
        }
      })
    }
  }
  chgEmail = () => {
    const { user } = this.state;
    let email = document.getElementById('email').value;
    let values = {
      id: user.id,
      backupEmail: email
    }
    if (email.trim() == '' || email.trim() == null) {
      message.warn('未输入邮箱！');
      this.setState({emailVisible: false});
    }else if(!(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/.test(email))){
      message.error('邮箱格式不正确！');
      this.setState({emailVisible: false});
    }else {
      axios.post('joker/users/update',{...values}).then(res => {
        let resposone = JSON.parse(res.request.response);
        if (resposone.Message){
          message.warning(resposone.Message);
        }else if (resposone.status == 1){
          this.refreshUser();
          this.setState({emailVisible: false});
          message.success('修改成功！');
        }else {
          message.error('修改失败！');
        }
      })
    }
  }
  handleFinish = e => {
    let values = {
      id: this.state.user.id,
      backupQuestion: e.question + ':' + e.answer
    }
    axios.post('joker/users/update',{...values}).then(res => {
      let resposone = JSON.parse(res.request.response);
      if (resposone.Message){
        message.warning(resposone.Message);
      }else if (resposone.status == 1){
        this.refreshUser();
        this.setState({questionVisible: false});
        message.success('设置成功！');
      }else {
        message.success('设置失败！');
      }
    })
  }
  getData = () => [
    {
      title: formatMessage(
        {
          id: 'userset.security.password',
        },
        {},
      ),
      description: (
        <>
          {formatMessage({
            id: 'userset.security.password-description',
          })}
          ：{this.state.user && this.state.user.password ? (
          this.state.user.password.length > 9 ? passwordStrength.strong :(
            this.state.user.password.length > 5 ? passwordStrength.medium :
              passwordStrength.weak
          )
        ) : ''}
        </>
      ),
      actions: [
        <a key="Modify" hidden={this.state.pwdInputVisible} onClick={this.chgVis}>
          <FormattedMessage id="userset.security.modify" defaultMessage="Modify" />
        </a>,
        <Input id='pwd' hidden={!this.state.pwdInputVisible}/>,
        <Button hidden={!this.state.pwdInputVisible}  onClick={this.chgPwd}>确定</Button>
      ],
    },
    {
      title: formatMessage(
        {
          id: 'userset.security.phone',
        },
        {},
      ),
      description: this.state.user && this.state.user.backupPhone ?
        <p><Badge status='success'/>{formatMessage(
        {
          id: 'userset.security.phone-description',
        },
        {},
      )}：{this.state.user && this.state.user.backupPhone ?(
        this.state.user.backupPhone.substring(0,3) + '****' + this.state.user.backupPhone.substring(7,12)) : ''}</p> :
        <p><Badge status='warning'/>{formatMessage(
          {
            id: 'userset.security.phone-no',
          },
          {},
        )}</p>,
      actions: [
        <a key="Modify" hidden={this.state.phoneInputVisible} onClick={this.chgVis2}>
          <FormattedMessage id="userset.security.modify" defaultMessage="Modify" />
        </a>,
        <Input id='phone' hidden={!this.state.phoneInputVisible}/>,
        <Button hidden={!this.state.phoneInputVisible} onClick={this.chgPhone}>确定</Button>
      ],
    },
    {
      title: formatMessage(
        {
          id: 'userset.security.question',
        },
        {},
      ),
      description: (this.state.backupQuestion == null || this.state.backupQuestion.question == '' || !this.state.user.backupQuestion) ?
        <p><Badge status='warning'/>{formatMessage(
        {
          id: 'userset.security.question-description',
        },
        {},
      )}</p> : <p><Badge status='success'/>{formatMessage(
        {
          id: 'userset.security.question-yes',
        }, {}
      )}</p>,
      actions: [
        <a key="Set" onClick={this.chgVis3}>
          <FormattedMessage id="userset.security.set" defaultMessage="Set" />
        </a>,
        <Input  hidden={true}/>,
        <Input  hidden={true}/>
      ],
    },
    {
      title: formatMessage(
        {
          id: 'userset.security.email',
        },
        {},
      ),
      description: this.state.user && this.state.user.backupEmail ?
        <p><Badge status='success'/>{formatMessage(
        {
          id: 'userset.security.email-description',
        },
        {},
      )}：{this.state.user && this.state.user.backupEmail ? this.state.user.backupEmail : ''}</p> :
        <p>
          <Badge status='warning'/>
          {formatMessage(
            {
              id: 'userset.security.email-no',
            },
            {},
          )}
        </p>,
      actions: [
        <a key="Modify" hidden={this.state.emailVisible} onClick={this.chgVis4}>
          <FormattedMessage id="userset.security.modify" defaultMessage="Modify" />
        </a>,
        <Input id='email' hidden={!this.state.emailVisible}/>,
        <Button hidden={!this.state.emailVisible} onClick={this.chgEmail}>确定</Button>
      ],
    },
  ];

  render() {
    const data = this.getData();
    return (
      <>
        <List
          itemLayout="horizontal"
          dataSource={data}
          renderItem={(item) => (
            <List.Item actions={item.actions}>
              <List.Item.Meta title={item.title} description={item.description} />
            </List.Item>
          )}
        />
        {this.state.questionVisible &&
          <Modal
            title='密保问题设置'
            visible={this.state.questionVisible}
            footer={null}
            onCancel={this.cancleVis}
            destroyOnClose
          >
            <Form
              layout="vertical"
              onFinish={this.handleFinish}
              initialValues={this.state.backupQuestion}
              hideRequiredMark
            >
              <Form.Item
                name="question"
                label="密保问题"
                rules={[
                  {
                    required: true,
                    message: '密保问题不能为空！'
                  }
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="answer"
                label="答案"
                rules={[
                  {
                    required: true,
                    message: '答案不能为空！'
                  }
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item style={{ whiteSpace: 'nowrap', textAlign: 'center' }}>
                <Button htmlType="submit" type="primary">
                  确定
                </Button>
                <Divider type='vertical'/>
                <Divider type='vertical'/>
                <Divider type='vertical'/>
                <Button type="primary" onClick={this.cancleVis}>
                  取消
                </Button>
              </Form.Item>
            </Form>
          </Modal>
        }
      </>
    );
  }
}

export default SecurityView;
